<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\User;
use App\Pay\Wechat;
use EasyWeChat\Work\Message;
use Illuminate\Http\Request;

class NotifyController extends Controller
{
    //余额支付
    public function money(Request $request): string
    {

        $out_trade_no = $request->input('out_trade_no');
        $amount       = $request->input('amount');
        $order = Order::where('sn',$out_trade_no)->first();
        if(!$order) {
            return 'fail';
        }
        if($order->pay_status == 1) {
            return 'success';
        }
        $user = User::where('id',$order->user_id)->first();
        if(!$user || ($user->money < $amount)) {
            return 'fail';
        }
        (new \App\Pay\Money)->handel($order,$user,$amount);
        return 'success';
    }
    //微信支付
    public function wechat(Request $request):string
    {
        $message = new Message();
        $out_trade_no = $message->out_trade_no;
        $amount = $message->amount->total;
        $order = Order::where('sn',$out_trade_no)->first();
        if(!$order) {
            return 'fail';
        }
        if($order->pay_status == 1) {
            return 'success';
        }
        $user = User::where('id',$order->user_id)->first();
        if(!$user || ($user->money < $amount)) {
            return 'fail';
        }
        (new \App\Pay\Wechat())->handel($order,$user,$amount);
        return 'success';
    }
    //微信支付
    public function Alipay(Request $request):string
    {
        $message = new Message();
        $out_trade_no = $message->out_trade_no;
        $amount = $message->amount->total;
        $order = Order::where('sn',$out_trade_no)->first();
        if(!$order) {
            return 'fail';
        }
        if($order->pay_status == 1) {
            return 'success';
        }
        $user = User::where('id',$order->user_id)->first();
        if(!$user || ($user->money < $amount)) {
            return 'fail';
        }
        (new \App\Pay\Alipay())->handel($order,$user,$amount);
        return 'success';
    }
}
